// 封装订阅发布模式

type Callback = (msg?: any) => void;
interface IEvents {
  [index: string]: Array<Callback>;
}

interface IEventBus {
  events: IEvents;
  on: (key: string, callback: Callback) => void;
  emit: (key: string, msg: any) => void;
  off: () => void;
}

const EventBus: IEventBus = {
  events: {},
  // 订阅方法
  on(key: string, callback: Callback) {
    // 如果已经存在一个和key相关的数组，就直接存函数进去，如果没有，就他创建一个
    if (!this.events[key]) {
      this.events[key] = [];
    }
    this.events[key].push(callback);
  },
  // 发布方法
  emit(key: string, msg?: any) {
    if (this.events[key]) {
      this.events[key].forEach((fn) => fn(msg));
    }
  },
  // 取消订阅的方法
  off() {},
};

export default EventBus;
